package com.yinhai.service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
import android.net.Uri;
import android.preference.PreferenceManager;
import android.provider.ContactsContract;
import android.telephony.TelephonyManager;
import android.util.Log;

import com.cmcc.groupcontacts.firewall.dao.model.CallInfoVO;
import com.yinhai.asynctask.AsyncTaskParam;
import com.yinhai.asynctask.ContactGroupTask;
import com.yinhai.asynctask.ContactGroupTaskForLogin;
import com.yinhai.asynctask.LoginCountTask;
import com.yinhai.asynctask.NameValueParam;
import com.yinhai.asynctask.OnlineContactTask;
import com.yinhai.asynctask.OnlineContactTaskForLogin;
import com.yinhai.cfg.LoginConfig;
import com.yinhai.cfg.LoginConfigUtil;
import com.yinhai.constant.Contact;
import com.yinhai.constant.UrlConstant;
import com.yinhai.dao.ContactGroupDaoImpl;
import com.yinhai.dao.ContactUserDaoImpl;
import com.yinhai.dao.OnlineContactUserDaoImpl;
import com.yinhai.map.ServiceMap;
import com.yinhai.model.ContactGroup;
import com.yinhai.model.ContactsUser;
import com.yinhai.model.LocalContactUserDetail;
import com.yinhai.model.OnlineContactDetail;
import com.yinhai.model.UserUserContact;
import com.yinhai.util.BufferException;
import com.yinhai.util.NullUtils;
import com.yinhai.util.PYSiteFunction;
import com.yinhai.util.PhoneSearchFunction;
import com.yinhai.util.PinYinUtil;
import com.yinhai.util.SiteObj;
import com.yinhai.util.Util;

public class ContactUserServiceImpl {
    // 以号码作为主键将联系人姓名保存起来
    public static Map<String, String> phoneNames = new HashMap<String, String>();
    
    public static Map<String, String> phoneThreads = new HashMap<String, String>();
    
    ContactUserDaoImpl contactUserDao;
    
    ContactGroupDaoImpl contactGroupDao;
    
    OnlineContactUserDaoImpl onlineContactUserDetail;
    
    ContentResolver contentResolver;
    
    private Context context;
    
    public ContactUserServiceImpl(Context context) {
        contactUserDao = new ContactUserDaoImpl(context);
        contactGroupDao = new ContactGroupDaoImpl(context);
        onlineContactUserDetail = new OnlineContactUserDaoImpl(context);
        contentResolver = context.getContentResolver();
        this.context = context;
    }
    
    /**
     * 初始话本地通讯，将本地通讯录数据存放到数据库中 1,为第一次登录不删除 0， 为删除数据，在同步
     */
    public boolean initLocalContact() {
        // 把数据库中的本地通讯录数据先删除，
        contactUserDao.execSql("delete from contact_user where type='"+Contact.CONTACT_TYPE_LOCAL+"'", new String[] {});
        // 获取本地通讯录数据
        // 实例化
        return init();
    }
    
    public void initOnlineContactNew(String phone) {
    	HttpPost httpRequest = getHttpPost(UrlConstant.LOCAL_URI+UrlConstant.DOWNLOADCONTACTS);

		List<NameValuePair> paramsUrl = new ArrayList<NameValuePair>();

		paramsUrl.add(new BasicNameValuePair("company_code", ""));
		paramsUrl.add(new BasicNameValuePair("download_type", ""));
		paramsUrl.add(new BasicNameValuePair("dept_values", ""));
		LoginConfig	log =LoginConfigUtil.getConfig(context);
		paramsUrl.add(new BasicNameValuePair("user_phone",phone));
		String resonsContent = null;
		try {
			// 发出HTTP request
			httpRequest.setEntity(new UrlEncodedFormEntity(paramsUrl,
					HTTP.UTF_8));
			// 取得HTTP response
			HttpResponse httpResponse = new DefaultHttpClient()
					.execute(httpRequest);
			// 若状态码为200 ok

			if (httpResponse.getStatusLine().getStatusCode() == 401) {
			} else if (httpResponse.getStatusLine().getStatusCode() != 200) {
			}
			Header[] headers = httpResponse.getHeaders("Content-Encoding");
			// 取出响应字符串
			resonsContent = getContentBytes2(httpResponse);
		} catch (Exception e) {
			e.printStackTrace();
			Log.e("xxxx", e.getMessage());
		}
        Map<String, Intent> serviceMap = ServiceMap.getMap();
        Intent syncContactService = serviceMap.get(Contact.SYNC_CONTACT_SERVICE);
        if(syncContactService != null) {
        	try{
        		context.stopService(syncContactService);
        		serviceMap.remove(Contact.SYNC_CONTACT_SERVICE);
        	}catch(Exception e) {
        		e.printStackTrace();
        	}
        }

    }
    private HttpPost getHttpPost(String url) {
		// 建立HTTP Post联机
		HttpPost httpRequest = new HttpPost(url);
		return httpRequest;
	}
    private String getContentBytes2(HttpResponse httpResponse)
			throws IOException, BufferException {
		try {
			String responseContent  = EntityUtils.toString(httpResponse.getEntity());
			JSONObject jsonObject = new JSONObject(responseContent);
			JSONArray groupss = (JSONArray) jsonObject.get("groups");
			JSONArray contacts = jsonObject.getJSONArray("contacts");
			String contactGroupVersion = jsonObject.getString("contactGroupVersion");
			//进度条每次添加好多数据
			ContactUserServiceImpl userService = new ContactUserServiceImpl(
					this.context);
			userService.gzipAddGroupNoProgress(groupss);
			Thread.sleep(2000);
			userService.gzipAddContactsNoProgress(contacts);
			SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this.context);
			Editor editor = sharedPreferences.edit();
			editor.putString("contactGroupVersion", contactGroupVersion);
		    editor.commit();
//		    ContactUserServiceImpl c = new ContactUserServiceImpl(context);
//            c.initName();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "";
	}
    public void initOnlineContact(String phone) {
        // 删除数据库中的分组信息
        contactGroupDao.execSql("delete from contact_group", null);
        
        // 把数据库中的本地通讯录数据先删除，
        contactUserDao.execSql("delete from contact_user where type=?", new String[] {Contact.CONTACT_TYPE_ONLINE});
        // initGroupToDB(phone);
        // initOnlineContactToDB(phone);
    }
    
    public void initOnlineContactLogin(String phone) {
        // 删除数据库中的分组信息
        contactGroupDao.execSql("delete from contact_group", null);
        
        // 把数据库中的本地通讯录数据先删除，
        contactUserDao.execSql("delete from contact_user where type=?", new String[] {Contact.CONTACT_TYPE_ONLINE});
        // initGroupToDBLogin(phone);
        // initOnlineContactToDBLogin(phone);
    }
    
    /**
     * //删除数据库中的分组信息一条记录
     * 
     */
    public void delOnlineContact(String group_id, String tel_phone) {
        contactUserDao.execSql("delete from contact_user where type=? and group_id=? and tel_phone=?", new String[] {
            Contact.CONTACT_TYPE_ONLINE, group_id, tel_phone});
    }
    
    /**
     * 删除全部
     */
    public void delContact() {
        // 删除数据库中的分组信息
        contactGroupDao.execSql("delete from contact_group", null);
        
        // 把数据库中的本地通讯录数据先删除，
        contactUserDao.execSql("delete from contact_user where type=?", new String[] {Contact.CONTACT_TYPE_ONLINE});
    }
    
    /**
     * 查找本地通讯录
     */
    public List<ContactsUser> findLocalContact() {
        return contactUserDao.rawQuery("select u.* from contact_user u where type=?",
            new String[] {Contact.CONTACT_TYPE_LOCAL});
    }
    
    /**
     * 黑白名单获取本地通讯录
     */
    public ArrayList<CallInfoVO> findLocalContactBlict() {
        List<Map<String, String>> maps =
            contactUserDao.query2MapList("select u.* from contact_user u where type=?",
                new String[] {Contact.CONTACT_TYPE_LOCAL});
        ArrayList<CallInfoVO> list = new ArrayList<CallInfoVO>();
        CallInfoVO c = null;
        for (Map<String, String> map : maps) {
            c = new CallInfoVO();
            c.setName(map.get("tel_phone"));
            c.setNumber(map.get("name"));
            c.setDate(System.currentTimeMillis());
            list.add(c);
        }
        return list;
    }
    
    /**
     * 获取集团通讯录
     * 
     * @return
     */
    public ArrayList<CallInfoVO> findLocalContactGroup() {
        List<Map<String, String>> maps =
            contactUserDao.query2MapList("select u.* from contact_user u where type=?",
                new String[] {Contact.CONTACT_TYPE_ONLINE});
        ArrayList<CallInfoVO> list = new ArrayList<CallInfoVO>();
        CallInfoVO c = null;
        for (Map<String, String> map : maps) {
            c = new CallInfoVO();
            c.setName(map.get("name"));
            c.setNumber(map.get("tel_phone"));
            c.setDate(System.currentTimeMillis());
            list.add(c);
        }
        return list;
    }
    
    /**
     * 获取集团通讯录
     * 
     * @return
     */
    public List<ContactsUser> findOnlineContact() {
        return contactUserDao.rawQuery("select u.* from contact_user u where type=?",
            new String[] {Contact.CONTACT_TYPE_ONLINE});
    }
    
    public Map<String, String> onlineContactMap() {
        List<Map<String, String>> maps =
            contactUserDao.query2MapList("select tel_phone,name from contact_user  where type=?",
                new String[] {Contact.CONTACT_TYPE_ONLINE});
        Map<String, String> namePhoneMap = new HashMap<String, String>();
        for (Map<String, String> map : maps) {
            namePhoneMap.put(map.get("tel_phone"), map.get("name"));
        }
        return namePhoneMap;
    }
    
    /**
     * 
     * 根据号码查询联系人
     * 
     * @param phone
     * @return
     */
    public ContactsUser findOnlineContactName(String phone) {
        ContactsUser user = null;
        List<ContactsUser> users =
            contactUserDao.rawQuery("select u.* from contact_user u where tel_phone=?", new String[] {phone});
        
        if (users != null && users.size() > 0) {
            user = users.get(0);
        }
        
        return user;
    }
    
    /**
     * 根据电话号码或者名字获取符合条件的本地和集团通讯录数据 拨号查询
     * 
     * @param content
     * @return
     */
    public List<ContactsUser> findContact(String content, int type) {
        // 1和0不匹配姓名
        // 匹配 先匹配姓名然后匹配集团短号，再匹配号码
        // 其他的根据排序
        List<ContactsUser> list = new ArrayList<ContactsUser>();
        List<ContactsUser> users = null;
        String whereString = "";
        if (type == -1) {
            whereString = "";
        } else if (type == 0) {
            whereString = " type = 1 and ";
        } else if (type == 1) {
            whereString = " type = 2 and ";
        }
        Contact.LIMIT1 = 30;
        if (content != null && content.length() > 0) {
            char first = content.charAt(0);
            int size = 0;
            if (('1' != first) && ('0' != first)) {
            	if(content.length() == 1) {
            		Contact.LIMIT1=10;
            	}
                // users =
                // contactUserDao.rawQuery("select u.* from contact_user u ",
                // null);
                users =
                    contactUserDao.rawQuery("select u.* from contact_user u where" + whereString
                        + " name_simple like '%" + content + "%' limit 0," + Contact.LIMIT1, null);
                // users =
                // contactUserDao.rawQuery("select u.* from contact_user u where name like '%卢%' limit 1,20",
                // null);
                for (ContactsUser user : users) {
                    user.setChangeType(Contact.MATCH_NAME);
                    if (user.getNameSimple().indexOf(content) > -1) {
                        user.setStart(user.getNameSimple().indexOf(content));
                        user.setEnd(user.getStart() + content.length());
                        list.add(user);
                    }
                    /*
                     * user.setStart(PhoneSearchFunction.GetSearchStr(PinYinUtil.
                     * getFirstSpell(user.getName())).indexOf(content)); user.setEnd(user.getStart()+content.length());
                     */
                    
                }
                size = list.size();
                if (size < Contact.LIMIT) {
                    users =
                        contactUserDao.rawQuery("select u.* from contact_user u where " + whereString
                            + " full_py_num like '%" + content + "%' limit 0," + (Contact.LIMIT1 - size), null);
                    for (ContactsUser user : users) {
                        user.setChangeType(Contact.MATCH_NAME);
                        SiteObj so = PYSiteFunction.GetQuanPYSite(user.getFullpynumsep(), content);
                        if (so != null) {
                            user.setStart(so.getBeginPoint());
                            user.setEnd((so.getEndPoint() + 1));
                            list.add(user);
                        }
                        
                    }
                }
            }
            size = list.size();
            if (size < Contact.LIMIT) {
                users =
                    contactUserDao.rawQuery("select u.* from contact_user u where " + whereString
                        + " short_num like '%" + content + "%' limit 0," + (Contact.LIMIT1 - size), null);
                for (ContactsUser user : users) {
                    user.setChangeType(Contact.MATHCH_TEL);
                    user.setStart(PhoneSearchFunction.GetSearchStr(user.getShortNum()).indexOf(content));
                    user.setEnd(user.getStart() + content.length());
                    list.add(user);
                }
            }
            size = list.size();
            if (size < Contact.LIMIT) {
                users =
                    contactUserDao.rawQuery("select u.* from contact_user u where " + whereString
                        + " tel_phone like '%" + content + "%' limit 0," + (Contact.LIMIT1 - size), null);
                for (ContactsUser user : users) {
                    user.setChangeType(Contact.MATHCH_TEL);
                    user.setStart(PhoneSearchFunction.GetSearchStr(user.getTelPhone()).indexOf(content));
                    user.setEnd(user.getStart() + content.length());
                    list.add(user);
                }
            }
        }
        return list;
    }
    
    /**
     * 获取分组信息 content 当content为空的时候查询所有的分组，当不为空的时候安名字模糊查询
     * 
     * @return
     */
    public List<ContactGroup> findGroup(String content) {
        if ((content != null) && (!"".equals(content.trim()))) {
            return contactGroupDao.rawQuery("select g.* from contact_group g where name like '%" + content.trim()
                + "%'", null);
        } else {
            return contactGroupDao.rawQuery("select g.* from contact_group g", null);
        }
        
    }
    
    public List<UserUserContact> searchGroup(String content) {
        List<UserUserContact> list = new ArrayList<UserUserContact>();
        List<ContactGroup> contacts = null;
        UserUserContact user = null;
        if ((content != null) && (!"".equals(content.trim()))) {
            contacts =
                contactGroupDao.rawQuery("select g.* from contact_group g where name like '%" + content.trim()
                    + "%' or py like '%" + content + "%'", null);
            for (ContactGroup u : contacts) {
                user = new UserUserContact();
                user.setId(u.getGroupId());
                user.setName(u.getName());
                user.setNum(u.getPeopleNume() + "");
                user.setType(Contact.CONTACT_TYPE_GROUP);
                user.setMatchType(Contact.MATCH_NAME);
                if (user.getName().contains(content)) {
                    user.setStart(user.getName().indexOf(content));
                } else {
                    user.setStart(PinYinUtil.getFirstSpell(user.getName()).indexOf(content));
                }
                
                user.setEnd(user.getStart() + content.length());
                list.add(user);
            }
            
            // 全拼匹配
            contacts = contactGroupDao.rawQuery("select g.* from contact_group g ", null);
            contacts =
                contactGroupDao.rawQuery("select g.* from contact_group g where full_py like '%" + content.trim()
                    + "%'", null);
            for (ContactGroup u : contacts) {
                user = new UserUserContact();
                user.setId(u.getGroupId());
                user.setName(u.getName());
                user.setNum(u.getPeopleNume() + "");
                user.setType(Contact.CONTACT_TYPE_GROUP);
                user.setMatchType(Contact.MATCH_NAME);
                
                SiteObj so = PYSiteFunction.GetQuanPYSite(u.getFullpysep(), content);
                if (so != null) {
                    user.setStart(so.getBeginPoint());
                    user.setEnd((so.getEndPoint() + 1));
                    list.add(user);
                }
            }
            // contacts =
            // contactGroupDao.rawQuery("select g.* from contact_group g where full_py like '%"+content+"%'",null);
        } else {
            contacts = contactGroupDao.rawQuery("select g.* from contact_group g", null);
            for (ContactGroup u : contacts) {
                user = new UserUserContact();
                user.setId(u.getGroupId());
                user.setName(u.getName());
                user.setNum(u.getPeopleNume() + "");
                user.setType(Contact.CONTACT_TYPE_GROUP);
                list.add(user);
            }
        }
        if (content == null) {
            UserUserContact g = new UserUserContact();
            g.setId(Contact.LOCAL_CONTACT_GROUP_ID);
            g.setName("本地通讯录");
            g.setNum("");
            g.setType(Contact.CONTACT_TYPE_GROUP);
            list.add(g);
        }
        
        return list;
    }
    
    public List<UserUserContact> searchNewGroup(String content, String parent_id, String companyID) {
        return searchNewGroup(content, parent_id, companyID, 0);
    }
    
    public List<UserUserContact> searchNewGroup(String content, String parent_id, String companyID, int groupType) {
        if (content != null) {
            content = content.toLowerCase().trim();
        }
        
        List<UserUserContact> list = new ArrayList<UserUserContact>();
        List<ContactGroup> contacts = null;
        UserUserContact user = null;
        if (groupType != 1) {
            
            if ((content != null) && (!"".equals(content))) {
                String sql = "select g.* from contact_group g where 1=1  and ";
                
                if (NullUtils.isNotEmpty(companyID)) {
                    sql += " company_id='" + companyID + "'  and ";
                }
                int type = 0;
                // 判断中文
                Pattern p = Pattern.compile("^[a-zA-Z]+$");
                Matcher m = p.matcher(content);
                if (m.matches()) {
                    type = 1;
                    sql += " (py like '%" + content + "%' or full_py like '%" + content + "%')";
                } else {
                    type = 2;
                    sql += " name like '%" + content + "%'";
                }
                contacts = contactGroupDao.rawQuery(sql, null);
                for (ContactGroup u : contacts) {
                    user = new UserUserContact();
                    user.setId(u.getGroupId());
                    user.setName(u.getName());
                    user.setNum(u.getPeopleNume() + "");
                    user.setType(Contact.CONTACT_TYPE_GROUP);
                    user.setFirstPy(u.getFirstpy());
                    user.setFullpy(u.getFullPY());
                    user.setMatchType(Contact.MATCH_NAME);
                    user.setFullpysep(u.getFullpysep());
                    user.setParent_id(u.getParent_id());
                    if (type == 1) {
                        if (user.getFirstPy().contains(content)) {
                            user.setStart(user.getFirstPy().indexOf(content));
                            user.setEnd(user.getStart() + content.length());
                            list.add(user);
                        } else {
                            SiteObj so = PYSiteFunction.GetQuanPYSite(u.getFullPY(), u.getFullpysep(), content);
                            if (so != null) {
                                user.setStart(so.getBeginPoint());
                                user.setEnd((so.getEndPoint() + 1));
                                list.add(user);
                            }
                        }
                    } else if (user.getName().contains(content)) {
                        user.setStart(user.getName().indexOf(content));
                        user.setEnd(user.getStart() + content.length());
                        list.add(user);
                    }
                    
                    if (list.size() > 100) {
                        break;
                    }
                }
                if (list.size() > 100) {
                    return list;
                }
                
            } else {
                String sql = "select g.* from contact_group g where   parent_id='" + parent_id + "'";
                if (NullUtils.isNotEmpty(companyID)) {
                    sql += " and company_id='" + companyID + "' ";
                }
                sql += " order by sort_num asc";
                contacts = contactGroupDao.rawQuery(sql, null);
                for (ContactGroup u : contacts) {
                    user = new UserUserContact();
                    user.setId(u.getGroupId());
                    user.setName(u.getName());
                    user.setNum(u.getPeopleNume() + "");
                    user.setType(Contact.CONTACT_TYPE_GROUP);
                    user.setFirstPy(u.getFirstpy());
                    user.setFullpy(u.getFullPY());
                    user.setFullpysep(u.getFullpysep());
                    user.setParent_id(u.getParent_id());
                    list.add(user);
                }
            }
        }
        if (content == null && parent_id.equals(companyID) && groupType != 2) {
            UserUserContact g = new UserUserContact();
            g.setId(Contact.LOCAL_CONTACT_GROUP_ID);
            g.setName("本地通讯录");
            g.setNum("");
            g.setType(Contact.CONTACT_TYPE_GROUP);
            g.setParent_id("0");
            // user.setParent_id("0");
            list.add(g);
        }
        return list;
    }
    
    public List<UserUserContact> searchContactUser(String content, String groupId, String companyID) {
        return searchContactUser(content, groupId, companyID, 0);
    }
    
    /**
     * 
     * <功能描述>
     * 
     * @param content
     * @param groupId
     * @param userType 0:查询全部 ；1：本地通讯录 2：集团通讯录
     * @return
     */
    public List<UserUserContact> searchContactUser(String content, String groupId, String companyID, int userType) {
        List<UserUserContact> list = new ArrayList<UserUserContact>();
        List<Map<String, String>> contacts = null;
        UserUserContact user = null;
        if ((content != null) && (!"".equals(content.trim()))) {
            StringBuffer sb = new StringBuffer();
            sb.append("select g.*,detail.duty as duty  from contact_user g left join online_contact_detail detail on g.userid=detail.userid where 1=1");
            if (NullUtils.isNotEmpty(companyID)
                && (NullUtils.isNotEmpty(groupId) && !Contact.LOCAL_CONTACT_GROUP_ID.equals(groupId))) {
                sb.append("  and (company_id='").append(companyID).append("'  or type=1)  ");
            }
            if ((groupId != null) && (!"".equals(groupId))) {
                sb.append(" and group_id='");
                sb.append(groupId);
                sb.append("'");
            }
            if (userType != 0) {
                sb.append(" and g.type=").append(userType).append("  ");
            }
            int type = 0;
            Pattern p = Pattern.compile("^[a-zA-Z]+$");
            Matcher m = p.matcher(content);
            if (m.matches()) {
                type = 1;
                sb.append(" and  (first_py like '%" + content + "%' or  full_py like '%" + content + "%')");
            } else {
                p = Pattern.compile("^[0-9]+$");
                m = p.matcher(content);
                if (m.matches()) {
                    type = 2;
                    sb.append(" and tel_phone like '%" + content + "%'");
                } else {
                    type = 3;
                    sb.append(" and g.name like '%" + content + "%'");
                }
            }
            
            /*
             * //查询集团通讯录 sb.append(" and type='"); sb.append(Contact.CONTACT_TYPE_ONLINE); sb.append("'");
             */
            // 姓名匹配
            contacts = contactUserDao.query2MapList(sb.toString(), null);
            if (contacts != null && !contacts.isEmpty()) {
                for (Map<String, String> map : contacts) {
                    user = new UserUserContact();
                    user.setId(map.get("userid"));
                    user.setName(map.get("name"));
                    
                    user.setParent_id(groupId);
                    user.setPhone(map.get("tel_phone"));
                    user.setType(map.get("type"));
                    user.setDuty(map.get("duty"));
                    user.setFullpysep(map.get("full_py_sep"));
                    user.setFullpy(map.get("full_py"));
                    user.setFirstPy(map.get("first_py"));
                    user.setImUserName(map.get("im_user_name"));
                    if (type == 1) {
                        user.setMatchType(Contact.MATCH_NAME);
                        if (user.getFirstPy().contains(content)) {
                            
                            user.setStart(user.getFirstPy().indexOf(content));
                            user.setEnd(user.getStart() + content.length());
                            list.add(user);
                        } else {
                            SiteObj so = PYSiteFunction.GetQuanPYSite(user.getFullpy(), user.getFullpysep(), content);
                            if (so != null) {
                                user.setStart(so.getBeginPoint());
                                user.setEnd((so.getEndPoint() + 1));
                                list.add(user);
                            }
                        }
                    } else if (type == 2) {
                        user.setMatchType(Contact.MATHCH_TEL);
                        user.setStart(user.getPhone().indexOf(content));
                        user.setEnd(user.getPhone().indexOf(content) + content.length());
                        list.add(user);
                    } else if (user.getName().contains(content)) {
                        user.setMatchType(Contact.MATCH_NAME);
                        user.setStart(user.getName().indexOf(content));
                        user.setEnd(user.getStart() + content.length());
                        list.add(user);
                    }
                    if (list.size() > 100) {
                        break;
                    }
                }
            }
            if (list.size() > 100) {
                return list;
            }
            
        } else {
            StringBuffer sb = new StringBuffer();
            sb.append("select g.*,detail.duty as duty  from contact_user g left join online_contact_detail detail on g.userid=detail.userid where ");
            if (NullUtils.isNotEmpty(companyID)
                && (NullUtils.isNotEmpty(groupId) && !Contact.LOCAL_CONTACT_GROUP_ID.equals(groupId))) {
                sb.append("  company_id='").append(companyID).append("' and ");
            }
            sb.append("group_id=? order by usort asc");
            contacts = contactUserDao.query2MapList(sb.toString(), new String[] {groupId});
            if (contacts != null && !contacts.isEmpty()) {
                for (Map<String, String> map : contacts) {
                    user = new UserUserContact();
                    user.setId(map.get("userid"));
                    user.setName(map.get("name"));
                    
                    user.setParent_id(groupId);
                    user.setPhone(map.get("tel_phone"));
                    user.setType(map.get("type"));
                    user.setDuty(map.get("duty"));
                    user.setFullpysep(map.get("full_py_sep"));
                    user.setFullpy(map.get("full_py"));
                    user.setFirstPy(map.get("first_py"));
                    user.setImUserName(map.get("im_user_name"));
                    list.add(user);
                }
            }
        }
        return list;
    }
    
    public List<ContactsUser> findContactsUserByGroupId(String groupId) {
        
        return contactUserDao.rawQuery("select g.* from contact_user g where group_id=?", new String[] {groupId});
    }
    
    public List<ContactsUser> findContactsUserByPhone(String phone) {
        
        return contactUserDao.rawQuery("select g.* from contact_user g where tel_phone=?", new String[] {phone});
    }
    
    /**
     * 根据电话号码查找集团联系人
     * 
     * @param phone
     * @return
     */
    public List<ContactsUser> findOnlineContactsUserByPhone(String phone) {
        if ((phone != null) && (!"".equals(phone))) {
            return contactUserDao.rawQuery("select g.* from contact_user g where  tel_phone=? and type = ?",
                new String[] {phone, Contact.CONTACT_TYPE_ONLINE});
        } else {
            return new ArrayList<ContactsUser>();
        }
        
    }
    
    public ContactsUser findOnlineContactsUserByIMUserName(String imUserName) {
        if (NullUtils.isNotEmpty(imUserName)) {
            List<ContactsUser> list =
                contactUserDao.rawQuery("select g.* from contact_user g where  im_user_name=? and type = ?",
                    new String[] {imUserName, Contact.CONTACT_TYPE_ONLINE});
            if (NullUtils.isNotEmpty(list)) {
                return list.get(0);
            }
        }
        return null;
        
    }
    
    /**
     * 根据电话号码查找本地联系人
     * 
     * @param phone
     * @return
     */
    public List<ContactsUser> findLocalContactsUserByPhone(String phone) {
        if ((phone != null) && (!"".equals(phone))) {
            return contactUserDao.rawQuery("select g.* from contact_user g where  tel_phone=? and type = ?",
                new String[] {phone, Contact.CONTACT_TYPE_LOCAL});
        } else {
            return new ArrayList<ContactsUser>();
        }
        
    }
    
    public void updateLocalContacts(ContactsUser cu) {
        contactUserDao.update(cu);
    }
    
    public long insertLocalContacts(ContactsUser cu) {
        long row = 0L;
        row = contactUserDao.insert(cu);
        return row;
    }
    
    /**
     * 初始化本地通讯录到数据库查询参数
     */
    public boolean init() {
        // long begin1 = System.currentTimeMillis();
        Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI; // 联系人Uri；
        // 查询的字段
        String[] projection =
            {ContactsContract.CommonDataKinds.Phone._ID, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
                ContactsContract.CommonDataKinds.Phone.DATA1, "sort_key",
                ContactsContract.CommonDataKinds.Phone.CONTACT_ID, ContactsContract.CommonDataKinds.Phone.PHOTO_ID,
                ContactsContract.CommonDataKinds.Phone.LOOKUP_KEY, ContactsContract.CommonDataKinds.Phone.CONTACT_ID};
        // 按照sort_key升序查詢
        Cursor cursor = contentResolver.query(uri, projection, null, null, "sort_key COLLATE LOCALIZED asc");
        List<ContactsUser> list = new ArrayList<ContactsUser>();
        ContactsUser cuser = null;
        boolean flag = true;
        Map<String,String> mapTreadId = new HashMap<String,String>();
        if (cursor != null && cursor.getCount() > 0) {
            cursor.moveToFirst(); // 游标移动到第一项
            for (int i = 0; i < cursor.getCount(); i++) {
                cursor.moveToPosition(i);
                String thread_id = cursor.getString(7);
                if(mapTreadId.get(thread_id) == null) {
                	mapTreadId.put(thread_id, "xx");
                } else {
                	continue;
                }
                String name = cursor.getString(1);
                String number = cursor.getString(2).trim().replaceAll(" ", "");
                // String sortKey = cursor.getString(3);
                // int contactId = cursor.getInt(4);
                // Long photoId = cursor.getLong(5);
                // String lookUpKey = cursor.getString(6);
                
                ContactsUser user = new ContactsUser();
                user.setTelPhone(number);
                user.setName(name);
                user.setType(Contact.CONTACT_TYPE_LOCAL);
                user.setGroupId(Contact.LOCAL_CONTACT_GROUP_ID);
                user.setGroupName(Contact.LOCAL_CONTACT_GROUP_NAME);
                user.setShortNum(PhoneSearchFunction.GetSearchStr(name));
                user.setNameSimple(PinYinUtil.getString2Num(PinYinUtil.getFirstSpell(name)));
                user.setFirstpy(PinYinUtil.getFirstSpell(name));
                user.setFullpy(PinYinUtil.getFullSpell(name));
                user.setFullpynum(PinYinUtil.getString2Num(PinYinUtil.getFullSpell(name)));
                user.setFullpysep(PinYinUtil.getFullSpellSep(name));
                user.setFullpynumsep(PinYinUtil.getString2Num(PinYinUtil.getFullSpellSep(name)));
                list.add(user);
                // Long id = contactUserDao.insert(user);
                phoneNames.put(number, name);
                phoneThreads.put(number, thread_id);
            }
            cursor.close();
            SQLiteDatabase db = this.context.openOrCreateDatabase("im.db", Context.MODE_PRIVATE, null);
            db.beginTransaction();
            for (int i = 0; i < list.size(); i++) {
                cuser = list.get(i);
                db.execSQL("INSERT INTO contact_user(name, tel_phone, type,group_id,group_name,userid,short_num,first_py,name_simple,full_py,full_py_num,full_py_sep,full_py_num_sep,usort)"
                    + " values(?, ?, ?,?,?,?,?,?,?,?,?,?,?,?)",
                    new Object[] {cuser.getName(), cuser.getTelPhone(), cuser.getType(), cuser.getGroupId(),
                        cuser.getGroupName(), cuser.getUserid(), cuser.getShortNum(), cuser.getFirstpy(),
                        cuser.getNameSimple(), cuser.getFullpy(), cuser.getFullpynum(), cuser.getFullpysep(),
                        cuser.getFullpynumsep(), cuser.getUsort()
                    
                    });
            }
            db.setTransactionSuccessful();
            db.endTransaction();
            // if(db !=null){
            db.close();
            // }
            
        } else {
            flag = false;
        }
        
        return flag;
    }
    
    /**
     * 初始化本地通讯录到数据库查询名字
     */
    public void initName() {
        // long begin1 = System.currentTimeMillis();
        Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI; // 联系人Uri；
        // 查询的字段
        String[] projection =
            {ContactsContract.CommonDataKinds.Phone._ID, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
                ContactsContract.CommonDataKinds.Phone.DATA1, "sort_key",
                ContactsContract.CommonDataKinds.Phone.CONTACT_ID, ContactsContract.CommonDataKinds.Phone.PHOTO_ID,
                ContactsContract.CommonDataKinds.Phone.LOOKUP_KEY, ContactsContract.CommonDataKinds.Phone.CONTACT_ID};
        // 按照sort_key升序查詢
        Cursor cursor = contentResolver.query(uri, projection, null, null, "sort_key COLLATE LOCALIZED asc");
        // List<ContactsUser> list = new ArrayList<ContactsUser>();
        // ContactsUser cuser=null;
        if (cursor != null && cursor.getCount() > 0) {
            cursor.moveToFirst(); // 游标移动到第一项
            for (int i = 0; i < cursor.getCount(); i++) {
                cursor.moveToPosition(i);
                String name = cursor.getString(1);
                String number = cursor.getString(2).trim().replaceAll(" ", "");
                String thread_id = cursor.getString(7);
                phoneNames.put(number, name);
                phoneThreads.put(number, thread_id);
            }
            
        }
        cursor.close();
        
        List<ContactsUser> findOnlineContact = findOnlineContact();
        for (int i = 0; i < findOnlineContact.size(); i++) {
            String number = findOnlineContact.get(i).getTelPhone();
            String name = findOnlineContact.get(i).getName();
            String shortnum1 = findOnlineContact.get(i).getShortNumNew();
            phoneNames.put(number, name);
            if (shortnum1 != null && !shortnum1.equals("") && !shortnum1.equals("null")) {
                phoneNames.put(shortnum1, name);
            }
            
        }
        
    }
    
    /**
     * 从接口初始话分组数据进入数据库
     */
    public void initGroupToDB(String phone) {
        ContactGroupTask groupTask = new ContactGroupTask(context);
        AsyncTaskParam taskParam = new AsyncTaskParam(UrlConstant.LOCAL_URI + UrlConstant.GET_CONTACTS_GROUPS);
        List<NameValuePair> list = new ArrayList<NameValuePair>();
        NameValueParam user_phone = new NameValueParam();
        user_phone.setName("user_phone");
        user_phone.setValue(phone);
        list.add(user_phone);
        taskParam.setPostParam(list);
        groupTask.execute(taskParam);
    }
    
    /*
     * 集团通讯录数据到数据库* 初始话
     */
    public void initOnlineContactToDB(String phone) {
        OnlineContactTask onlineTask = new OnlineContactTask(context);
        AsyncTaskParam taskParam = new AsyncTaskParam(UrlConstant.LOCAL_URI + UrlConstant.GET_CONTACTS);
        List<NameValuePair> list = new ArrayList<NameValuePair>();
        NameValueParam user_phone = new NameValueParam();
        user_phone.setName("user_phone");
        user_phone.setValue(phone);
        list.add(user_phone);
        taskParam.setPostParam(list);
        onlineTask.execute(taskParam);
    }
    
    /**
     * 登录时从接口初始话分组数据进入数据库
     */
    public void initGroupToDBLogin(String phone) {
        ContactGroupTaskForLogin groupTask = new ContactGroupTaskForLogin(context);
        AsyncTaskParam taskParam = new AsyncTaskParam(UrlConstant.LOCAL_URI + UrlConstant.GET_CONTACTS_GROUPS);
        List<NameValuePair> list = new ArrayList<NameValuePair>();
        NameValueParam user_phone = new NameValueParam();
        user_phone.setName("user_phone");
        user_phone.setValue(phone);
        list.add(user_phone);
        taskParam.setPostParam(list);
        groupTask.execute(taskParam);
    }
    
    /*
     * 登录时集团通讯录数据到数据库* 初始话
     */
    public void initOnlineContactToDBLogin(String phone) {
        OnlineContactTaskForLogin onlineTask = new OnlineContactTaskForLogin(context);
        AsyncTaskParam taskParam = new AsyncTaskParam(UrlConstant.LOCAL_URI + UrlConstant.GET_CONTACTS);
        List<NameValuePair> list = new ArrayList<NameValuePair>();
        NameValueParam user_phone = new NameValueParam();
        user_phone.setName("user_phone");
        user_phone.setValue(phone);
        list.add(user_phone);
        taskParam.setPostParam(list);
        onlineTask.execute(taskParam);
    }
    
    /**
     * 获取本地通讯录联系人详情
     * 
     * @return
     */
    public LocalContactUserDetail findLocalContactUserDetail(String userId) {
        LocalContactUserDetail detail = new LocalContactUserDetail();
        detail.setName("测试");
        detail.setTelPhone("13997637283");
        return detail;
    }
    
    /**
     * 根据用户ID 获取集团通讯录中联系人详情
     * 
     * @param userId
     * @return
     */
    public OnlineContactDetail findOnlineContactDetail(String userId) {
        OnlineContactDetail detail = null;
        List<OnlineContactDetail> details =
            onlineContactUserDetail.rawQuery("select d.* from online_contact_detail d where d.userid=?",
                new String[] {userId});
        if ((details != null) && (details.size() > 0)) {
            detail = details.get(0);
        } else {
            detail = new OnlineContactDetail();
        }
        return detail;
    }
    
    /**
     * 根据用户手机号码 获取集团通讯录中联系人详情
     * 
     * @param telphone
     * @return
     */
    public OnlineContactDetail findOnlinePhoneContactDetail(String telphone) {
        OnlineContactDetail detail = null;
        List<OnlineContactDetail> details =
            onlineContactUserDetail.rawQuery("select d.* from online_contact_detail d where d.telphone=?",
                new String[] {telphone});
        if ((details != null) && (details.size() > 0)) {
            detail = details.get(0);
        } else {
            detail = new OnlineContactDetail();
        }
        return detail;
    }
    
    public long count() {
        return contactUserDao.query("select count(1) from contact_user");
    }
    
    /**
     * 通过电话号码查询用户姓名
     */
    public List<ContactsUser> findContactDispalyName(String phone) {
        return contactUserDao.rawQuery("select u.* from contact_user u where tel_phone=? or short_num_new=?", new String[] {phone,phone});
    }
    
    public void findCount() {
        TelephonyManager phoneMgr = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
        String phoneNum = phoneMgr.getLine1Number();// 本机电话号码
        LoginCountTask loginCountTask = new LoginCountTask(context);
        AsyncTaskParam taskParam = new AsyncTaskParam(UrlConstant.CONTACT_USER_URI + UrlConstant.RCV_BY_MOBILE);
        NameValueParam n = new NameValueParam();
        n.setName("vUmobile");
        String deviceid = phoneMgr.getDeviceId();
        String tel = phoneMgr.getLine1Number();
        String imei = phoneMgr.getSimSerialNumber();
        String imsi = phoneMgr.getSubscriberId();
        n.setValue(phoneNum);
        // n.setValue("15803081472");
        List<NameValuePair> postParam = new ArrayList<NameValuePair>();
        postParam.add(n);
        taskParam.setPostParam(postParam);
        loginCountTask.execute(taskParam);
    }
    
    // 判断是否同步了online通讯录
    public boolean isUpdatedOnlineContactUser() {
        boolean flag = false;
        List<ContactGroup> contactGroupList = contactGroupDao.rawQuery("select g.* from contact_group g", null);
        if (contactGroupList != null && contactGroupList.size() > 0) {
            flag = true;
        }
        return flag;
    }
    
    public void gzipAddGroup(JSONArray ja, int insertSize, int pageCount, ProgressDialog downloadProgressDialog) {
        List<JSONObject> groups = new ArrayList<JSONObject>();
        JSONObject jo = null;
        String groupSql =
            "INSERT INTO contact_group(id, groupid, name,people_num,py,full_py,first_py,name_simple,full_py_num,full_py_sep,full_py_num_sep,parent_id,sort_num,company_id)"
                + " values(?, ?, ?,?,?,?,?,?,?,?,?,?,?,?)";
        SQLiteDatabase db = this.context.openOrCreateDatabase("im.db", Context.MODE_PRIVATE, null);
        try {
            SQLiteStatement stat = db.compileStatement(groupSql);
            db.beginTransaction();
            for (int i = 0; i < ja.length(); i++) {
                jo = ja.getJSONObject(i);
                stat.bindString(1, jo.getString("id"));
                stat.bindString(2, jo.getString("groupId"));
                stat.bindString(3, jo.getString("name"));
                stat.bindLong(4, jo.getInt("peopleNume"));
                stat.bindString(5, jo.getString("py"));
                stat.bindString(6, jo.getString("fullPY"));
                stat.bindString(7, jo.getString("firstpy"));
                stat.bindString(8, jo.getString("nameSimple"));
                stat.bindString(9, jo.getString("fullpynum"));
                stat.bindString(10, jo.getString("fullpysep"));
                stat.bindString(11, jo.getString("fullpynumsep"));
                stat.bindString(12, jo.getString("parent_id"));
                stat.bindLong(13, jo.getInt("sortNum"));
                stat.bindString(14, jo.getString("compId"));
                long result = stat.executeInsert();
            }
            db.setTransactionSuccessful();
            db.endTransaction();
            insertSize = insertSize + pageCount;
            downloadProgressDialog.setProgress(50 + insertSize);
        } catch (Exception e) {
            e.printStackTrace();
            Util.showMsg(context, "同步部门信息失败" + e.getMessage());
        } finally {
            if (db != null && db.isOpen()) {
                db.close();
            }
        }
    }
    public void gzipAddGroupNoProgress(JSONArray ja) {
    	List<JSONObject> groups = new ArrayList<JSONObject>();
    	JSONObject jo = null;
    	String groupSql =
    			"INSERT INTO contact_group(id, groupid, name,people_num,py,full_py,first_py,name_simple,full_py_num,full_py_sep,full_py_num_sep,parent_id,sort_num,company_id)"
    					+ " values(?, ?, ?,?,?,?,?,?,?,?,?,?,?,?)";
    	SQLiteDatabase db = this.context.openOrCreateDatabase("im.db", Context.MODE_PRIVATE, null);
    	try {
    		SQLiteStatement stat = db.compileStatement(groupSql);
    		db.beginTransaction();
    		for (int i = 0; i < ja.length(); i++) {
    			jo = ja.getJSONObject(i);
    			stat.bindString(1, jo.getString("id"));
    			stat.bindString(2, jo.getString("groupId"));
    			stat.bindString(3, jo.getString("name"));
    			stat.bindLong(4, jo.getInt("peopleNume"));
    			stat.bindString(5, jo.getString("py"));
    			stat.bindString(6, jo.getString("fullPY"));
    			stat.bindString(7, jo.getString("firstpy"));
    			stat.bindString(8, jo.getString("nameSimple"));
    			stat.bindString(9, jo.getString("fullpynum"));
    			stat.bindString(10, jo.getString("fullpysep"));
    			stat.bindString(11, jo.getString("fullpynumsep"));
    			stat.bindString(12, jo.getString("parent_id"));
    			stat.bindLong(13, jo.getInt("sortNum"));
    			stat.bindString(14, jo.getString("compId"));
    			long result = stat.executeInsert();
    		}
    		db.setTransactionSuccessful();
    		db.endTransaction();
    	} catch (Exception e) {
    		e.printStackTrace();
    		Util.showMsg(context, "同步部门信息失败" + e.getMessage());
    	} finally {
    		if (db != null && db.isOpen()) {
    			db.close();
    		}
    	}
    }
    
    public void gzipAddContacts(JSONArray ja, int insertSize, int pageCount, ProgressDialog downloadProgressDialog) {
        SQLiteDatabase db = this.context.openOrCreateDatabase("im.db", Context.MODE_PRIVATE, null);
        String phoneNew = null;
        String nameNew = null;
        try {
            JSONObject jo = null;
            OnlineContactDetail detail = null;
            List<JSONObject> list = new ArrayList<JSONObject>();
            contactUserDao.execSql("delete from contact_user where type=?", new String[] {Contact.CONTACT_TYPE_ONLINE});
            onlineContactUserDetail.execSql("delete from online_contact_detail", null);
            String contactUserSql =
                "INSERT INTO contact_user(name, tel_phone, type,group_id,group_name,userid,short_num,first_py,name_simple,full_py,full_py_num,full_py_sep,full_py_num_sep,usort,type,isshowtel,im_user_name,company_id,short_num_new)"
                    + " values(?, ?, ?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
            String detailSql =
                "INSERT INTO online_contact_detail( userid, name,company,duty,telphone,shortphone,mobile,email,isshowtel)"
                    + " values(?, ?, ?,?,?,?,?,?,?)";
            SQLiteStatement stat = db.compileStatement(contactUserSql);
            db.beginTransaction();
            
            for (int i = 0; i < ja.length(); i++) {
                jo = ja.getJSONObject(i);
                nameNew = jo.getString("uname");
                stat.bindString(1, nameNew);
                stat.bindString(2, jo.getString("umobile"));
                stat.bindString(3, Contact.CONTACT_TYPE_ONLINE);
                stat.bindString(4, jo.getString("ctgroupid"));
                stat.bindString(5, jo.getString("ctgroupname"));
                stat.bindString(6, jo.getString("recid"));
                stat.bindString(7, jo.getString("ordernum"));
                stat.bindString(8, jo.getString("firstpy"));
                stat.bindString(9, jo.getString("nameSimple"));
                stat.bindString(10, jo.getString("fullpy"));
                stat.bindString(11, jo.getString("fullpynum"));
                stat.bindString(12, jo.getString("fullpysep"));
                stat.bindString(13, jo.getString("fullpynumsep"));
                stat.bindLong(14, Integer.parseInt(jo.getString("ordernum")));
                stat.bindString(15, Contact.CONTACT_TYPE_ONLINE);
                stat.bindString(16, jo.getString("isshowtel"));
                stat.bindString(17, jo.getString("im_user_name"));
                stat.bindString(18, jo.getString("compId"));
                stat.bindString(19, jo.getString("shortPhone"));
                phoneNames.put(jo.getString("umobile"), nameNew);
                phoneNew = jo.getString("shortPhone");
                if (phoneNew != null && !phoneNew.equals("") && !phoneNew.equals("null")) {
                    phoneNames.put(phoneNew, nameNew);
                }
                long result = stat.executeInsert();
                // db.execSQL(detailSql,
                // new Object[] {jo.getString("recid"), jo.getString("uname"), jo.getString("company"),
                // jo.getString("duty"), jo.getString("umobile"), jo.getString("shortPhone"),
                // jo.getString("mobile"), jo.getString("email"), jo.getString("isshowtel")});
            }
            db.setTransactionSuccessful();
            db.endTransaction();
            SQLiteStatement stat1 = db.compileStatement(detailSql);
            db.beginTransaction();
            for (int i = 0; i < ja.length(); i++) {
                jo = ja.getJSONObject(i);
                stat1.bindString(1, jo.getString("recid"));
                stat1.bindString(2, jo.getString("uname"));
                stat1.bindString(3, jo.getString("company"));
                stat1.bindString(4, jo.getString("duty"));
                stat1.bindString(5, jo.getString("umobile"));
                stat1.bindString(6, jo.getString("shortPhone"));
                stat1.bindString(7, jo.getString("mobile"));
                stat1.bindString(8, jo.getString("email"));
                stat1.bindString(9, jo.getString("isshowtel"));
                long result = stat1.executeInsert();
            }
            db.setTransactionSuccessful();
            db.endTransaction();
            insertSize = insertSize + pageCount;
            downloadProgressDialog.setProgress(50 + insertSize);
        } catch (JSONException e) {
            e.printStackTrace();
            Util.showMsg(context, "同步联系人失败" + e.getMessage());
        } finally {
            if (db != null && db.isOpen()) {
                db.close();
            }
        }
    }
    public void gzipAddContactsNoProgress(JSONArray ja) {
    	SQLiteDatabase db = this.context.openOrCreateDatabase("im.db", Context.MODE_PRIVATE, null);
    	String phoneNew = null;
    	String nameNew = null;
    	try {
    		JSONObject jo = null;
    		OnlineContactDetail detail = null;
    		List<JSONObject> list = new ArrayList<JSONObject>();
    		contactUserDao.execSql("delete from contact_user where type=?", new String[] {Contact.CONTACT_TYPE_ONLINE});
    		onlineContactUserDetail.execSql("delete from online_contact_detail", null);
    		String contactUserSql =
    				"INSERT INTO contact_user(name, tel_phone, type,group_id,group_name,userid,short_num,first_py,name_simple,full_py,full_py_num,full_py_sep,full_py_num_sep,usort,type,isshowtel,im_user_name,company_id,short_num_new)"
    						+ " values(?, ?, ?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
    		String detailSql =
    				"INSERT INTO online_contact_detail( userid, name,company,duty,telphone,shortphone,mobile,email,isshowtel)"
    						+ " values(?, ?, ?,?,?,?,?,?,?)";
    		SQLiteStatement stat = db.compileStatement(contactUserSql);
    		db.beginTransaction();
    		
    		for (int i = 0; i < ja.length(); i++) {
    			jo = ja.getJSONObject(i);
    			nameNew = jo.getString("uname");
    			stat.bindString(1, nameNew);
    			stat.bindString(2, jo.getString("umobile"));
    			stat.bindString(3, Contact.CONTACT_TYPE_ONLINE);
    			stat.bindString(4, jo.getString("ctgroupid"));
    			stat.bindString(5, jo.getString("ctgroupname"));
    			stat.bindString(6, jo.getString("recid"));
    			stat.bindString(7, jo.getString("ordernum"));
    			stat.bindString(8, jo.getString("firstpy"));
    			stat.bindString(9, jo.getString("nameSimple"));
    			stat.bindString(10, jo.getString("fullpy"));
    			stat.bindString(11, jo.getString("fullpynum"));
    			stat.bindString(12, jo.getString("fullpysep"));
    			stat.bindString(13, jo.getString("fullpynumsep"));
    			stat.bindLong(14, Integer.parseInt(jo.getString("ordernum")));
    			stat.bindString(15, Contact.CONTACT_TYPE_ONLINE);
    			stat.bindString(16, jo.getString("isshowtel"));
    			stat.bindString(17, jo.getString("im_user_name"));
    			stat.bindString(18, jo.getString("compId"));
    			stat.bindString(19, jo.getString("shortPhone"));
    			phoneNames.put(jo.getString("umobile"), nameNew);
    			phoneNew = jo.getString("shortPhone");
    			if (phoneNew != null && !phoneNew.equals("") && !phoneNew.equals("null")) {
    				phoneNames.put(phoneNew, nameNew);
    			}
    			long result = stat.executeInsert();
    		}
    		db.setTransactionSuccessful();
    		db.endTransaction();
    		SQLiteStatement stat1 = db.compileStatement(detailSql);
    		db.beginTransaction();
    		for (int i = 0; i < ja.length(); i++) {
    			jo = ja.getJSONObject(i);
    			stat1.bindString(1, jo.getString("recid"));
    			stat1.bindString(2, jo.getString("uname"));
    			stat1.bindString(3, jo.getString("company"));
    			stat1.bindString(4, jo.getString("duty"));
    			stat1.bindString(5, jo.getString("umobile"));
    			stat1.bindString(6, jo.getString("shortPhone"));
    			stat1.bindString(7, jo.getString("mobile"));
    			stat1.bindString(8, jo.getString("email"));
    			stat1.bindString(9, jo.getString("isshowtel"));
    			long result = stat1.executeInsert();
    		}
    		db.setTransactionSuccessful();
    		db.endTransaction();
    	} catch (JSONException e) {
    		e.printStackTrace();
    		Util.showMsg(context, "同步联系人失败" + e.getMessage());
    	} finally {
    		if (db != null && db.isOpen()) {
    			db.close();
    		}
    	}
    }
    
    /**
     * 根据部门ID查询联系人信息
     * 
     * @param deptId
     * @return
     */
    public List<ContactsUser> findContactUserByDeptId(String deptId) {
        return contactUserDao.rawQuery("select u.* from contact_user u where group_id=?", new String[] {deptId,Contact.CONTACT_TYPE_ONLINE});
    }
    public List<ContactsUser> findContactUserByLoginName(String loginName) {
        return contactUserDao.rawQuery("select u.* from contact_user u where telPhone=? and type = ?", new String[] {loginName});
    }
    /**
     * 根据上级ID查询，当前部门下的子部门
     * 
     * @param deptId
     * @return
     */
    public List<ContactGroup> findGroupByParentId(String deptId) {
        return contactGroupDao.rawQuery("select g.* from contact_group g where parent_id = '" + deptId + "'", null);
    }
    
    /**
     * 短信群发时选择部门方法
     * 
     * @param userMap
     * @param groupMap
     * @param deptId
     */
    public void findDeptAllPersonAndDep(Map<String, ContactsUser> userMap, Map<String, ContactGroup> groupMap,
        String deptId) {
        List<ContactsUser> users = findContactUserByDeptId(deptId);
        for (ContactsUser user : users) {
            userMap.put(user.getId() + "", user);
        }
        users = null;
        List<ContactGroup> groups = findGroupByParentId(deptId);
        if (groups != null) {
            for (ContactGroup group : groups) {
                groupMap.put(group.getId(), group);
                findDeptAllPersonAndDep(userMap, groupMap, group.getId());
            }
        }
    }
    
}
